package com.example.gbuffer.Component.Framebuffer;

import android.opengl.GLES32;
import android.util.Log;

import com.example.gbuffer.Utils.OpenGLUtils;

public class ScreenFramebuffer extends Framebuffer{

    private int[] m_color_buffer = new int[1];
    private int[] m_render_buffer = new int[1];

    private int m_width;
    private int m_height;
    private String LOG_TAG = "ScreenFramebuffer";

    public ScreenFramebuffer(int width, int height){
        super();

        if ( !init(width, height) ) {
            Log.w(LOG_TAG, "init geo framebuffer failed.");
        }
    }

    public int getScreenTextureId(){ return m_color_buffer[0];}

    protected boolean init(int width, int height) {

        m_width = width;
        m_height = height;

        GLES32.glGenFramebuffers(1, m_buffer, 0);
        GLES32.glBindFramebuffer(GLES32.GL_FRAMEBUFFER, m_buffer[0]);

        // - 颜色缓冲
        GLES32.glGenTextures(1, m_color_buffer, 0);
        GLES32.glBindTexture(GLES32.GL_TEXTURE_2D, m_color_buffer[0]);
        GLES32.glTexImage2D(GLES32.GL_TEXTURE_2D, 0, GLES32.GL_RGB16F, m_width, m_height, 0, GLES32.GL_RGB, GLES32.GL_FLOAT, null);
        GLES32.glTexParameteri(GLES32.GL_TEXTURE_2D, GLES32.GL_TEXTURE_MIN_FILTER, GLES32.GL_LINEAR);
        GLES32.glTexParameteri(GLES32.GL_TEXTURE_2D, GLES32.GL_TEXTURE_MAG_FILTER, GLES32.GL_LINEAR);
        GLES32.glFramebufferTexture2D(GLES32.GL_FRAMEBUFFER, GLES32.GL_COLOR_ATTACHMENT0, GLES32.GL_TEXTURE_2D, m_color_buffer[0], 0);

        // - 深度缓冲
        GLES32.glGenRenderbuffers(1, m_render_buffer, 0);
        GLES32.glBindRenderbuffer(GLES32.GL_RENDERBUFFER, m_render_buffer[0]);
        GLES32.glRenderbufferStorage(GLES32.GL_RENDERBUFFER, GLES32.GL_DEPTH_COMPONENT24, m_width, m_height);
        GLES32.glFramebufferRenderbuffer(GLES32.GL_FRAMEBUFFER, GLES32.GL_DEPTH_ATTACHMENT, GLES32.GL_RENDERBUFFER, m_render_buffer[0]);

        GLES32.glBindFramebuffer(GLES32.GL_FRAMEBUFFER, 0);
        GLES32.glBindTexture(GLES32.GL_TEXTURE_2D, 0);
        return OpenGLUtils.checkFramebufferStatus();
    }

    @Override
    public void bind() {
        GLES32.glBindFramebuffer(GLES32.GL_FRAMEBUFFER, m_buffer[0]);
    }
}
